package org.m8.auth.security.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.m8.auth.config.SecurityConfig;
import org.m8.auth.security.LoginUser;
import org.m8.auth.security.util.SecurityFrameworkUtils;
import org.m8.auth.model.OAuth2AccessTokenDO;
import org.m8.auth.model.OAuth2TokenService;
import org.m8.util.JsonUtil;
import org.m8.util.exception.ServiceException;
import org.m8.util.model.CommonResult;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * Token 过滤器，验证 token 的有效性
 * 验证通过后，获得 {@link LoginUser} 信息，并加入到 Spring Security 上下文
 *
 * @author yidanjun
 */
@RequiredArgsConstructor
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private final SecurityConfig securityConfig;


    private final OAuth2TokenService auth2TokenService;
    @Override
    @SuppressWarnings("NullableProblems")
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String token = SecurityFrameworkUtils.obtainAuthorization(request,
                securityConfig.getTokenHeader(), securityConfig.getTokenParameter());
        if (StrUtil.isNotEmpty(token)) {
            try {
                // 1.1 基于 token 构建登录用户
                LoginUser loginUser = buildLoginUserByToken(token);

                // 2. 设置当前用户
                if (loginUser != null) {
                    SecurityFrameworkUtils.setLoginUser(loginUser, request);
                }
            } catch (Throwable ex) {
                String errMsg = ex.getMessage() + ". cause-msg:" + ex.getCause().getMessage();
                CommonResult<?> result = CommonResult.error(500, errMsg);
                String content =  JsonUtil.stringify(result);
                JakartaServletUtil.write(response, content, MediaType.APPLICATION_JSON_UTF8_VALUE);
                return;
            }
        }

        // 继续过滤链
        chain.doFilter(request, response);
    }

    private LoginUser buildLoginUserByToken(String token) {
        try {
            OAuth2AccessTokenDO accessToken = auth2TokenService.checkAccessToken(token);
            if (accessToken == null) {
                return null;
            }
            // 构建登录用户
            LoginUser loginUser = new LoginUser();
            loginUser.setId(accessToken.getUserId());
            return loginUser;
        } catch (ServiceException serviceException) {
            // 校验 Token 不通过时，考虑到一些接口是无需登录的，所以直接返回 null 即可
            return null;
        }
    }


}
